
from agents import (
    alternative_suppliers_agent,
    company_overview_agent,
    cost_drivers_agent,
    kraljic_agent,
    pestle_agent,
    porter_agent,
    report_compiler_agent,
    switching_barriers_agent,
)
from agno.workflow import Condition, Parallel, Step, Workflow
from agno.workflow.types import StepInput
from models import ProcurementAnalysisRequest


# def should_run_analysis(analysis_type: str):
#     """Create conditional evaluator for analysis types"""
#
#     def evaluator(step_input: StepInput) -> bool:
#         # 正确访问 StepInput 的 message 属性，而不是 input 属性
#         request_data = step_input.message
#         if isinstance(request_data, ProcurementAnalysisRequest):
#             return analysis_type in request_data.analyses_requested
#         return False
#
#     return evaluator

def should_run_analysis(analysis_type: str):
    def evaluator(step_input: StepInput) -> bool:
        print(f"=== Debug StepInput ===")
        print(f"StepInput type: {type(step_input)}")
        print(f"StepInput attributes: {dir(step_input)}")

        # 尝试不同的属性
        if hasattr(step_input, 'input'):
            print(f"step_input.input: {step_input.input}")
            request_data = step_input.input
        elif hasattr(step_input, 'message'):
            print(f"step_input.message: {step_input.message}")
            request_data = step_input.message
        else:
            print("No input or message attribute found")
            return False

        print(f"request_data type: {type(request_data)}")
        print(f"request_data: {request_data}")
        print("========================")

        if isinstance(request_data, ProcurementAnalysisRequest):
            return analysis_type in request_data.analyses_requested
        return False

    return evaluator


company_overview_step = Step(
    name="Company Overview",
    agent=company_overview_agent,
    description="Research and analyze the target company",
)

switching_barriers_step = Step(
    name="Switching Barriers Analysis",
    agent=switching_barriers_agent,
    description="Analyze supplier switching barriers and costs",
)

pestle_step = Step(
    name="PESTLE Analysis",
    agent=pestle_agent,
    description="Conduct PESTLE analysis for procurement strategy",
)

porter_step = Step(
    name="Porter's Five Forces Analysis",
    agent=porter_agent,
    description="Analyze competitive forces in the supply market",
)

kraljic_step = Step(
    name="Kraljic Matrix Analysis",
    agent=kraljic_agent,
    description="Position category on Kraljic Matrix",
)

cost_drivers_step = Step(
    name="Cost Drivers Analysis",
    agent=cost_drivers_agent,
    description="Analyze cost structure and volatility",
)

alternative_suppliers_step = Step(
    name="Alternative Suppliers Research",
    agent=alternative_suppliers_agent,
    description="Identify and evaluate alternative suppliers",
)

report_compilation_step = Step(
    name="Report Compilation",
    agent=report_compiler_agent,
    description="Compile comprehensive procurement analysis report", # 采购分析报告
)

procurement_workflow = Workflow(
    name="Procurement Analysis Workflow",
    description="Comprehensive procurement intelligence using multiple strategic frameworks",
    steps=[
        company_overview_step,
        Parallel(
            Condition(
                evaluator=should_run_analysis("switching_barriers"),
                steps=[switching_barriers_step],
                name="Switching Barriers Condition",
            ),
            Condition(
                evaluator=should_run_analysis("pestle"),
                steps=[pestle_step],
                name="PESTLE Condition",
            ),
            Condition(
                evaluator=should_run_analysis("porter"),
                steps=[porter_step],
                name="Porter's Five Forces Condition",
            ),
            Condition(
                evaluator=should_run_analysis("kraljic"),
                steps=[kraljic_step],
                name="Kraljic Matrix Condition",
            ),
            Condition(
                evaluator=should_run_analysis("cost_drivers"),
                steps=[cost_drivers_step],
                name="Cost Drivers Condition",
            ),
            Condition(
                evaluator=should_run_analysis("alternative_suppliers"),
                steps=[alternative_suppliers_step],
                name="Alternative Suppliers Condition",
            ),
            name="Analysis Phase",
        ), # 并行执行的分析阶段
        report_compilation_step, # 最后报告生成
    ],
)

# if __name__ == "__main__":
#     analysis_details = ProcurementAnalysisRequest(
#         companies=["Tesla", "Ford"],
#         category_name="Electric Vehicle Components",
#         analyses_requested=[
#             # "switching_barriers",
#             "pestle",
#             "porter",
#             # "kraljic",
#             # "cost_drivers",
#             # "alternative_suppliers",
#         ],
#         region="Global",
#         annual_spend=50,
#         incumbent_suppliers=["CATL", "Panasonic", "LG Energy Solution"],
#     )
#     procurement_workflow.print_response(
#         input=analysis_details,
#         stream=True,
#         stream_events=True,
#     )

if __name__ == "__main__":
    # 简化测试
    analysis_details = ProcurementAnalysisRequest(
        companies=["易方达基金"],
        category_name="金融IT系统",
        analyses_requested=["pestle"],  # 只测试一个分析
        region="中国",
        annual_spend=25000000,
        incumbent_suppliers=["恒生电子"],
    )

    # 正确的方式：使用工作流程的测试功能
    procurement_workflow.print_response(
        input=analysis_details,
        stream=True,
        stream_events=True,
    )

    # analysis_details = ProcurementAnalysisRequest(
    #     companies=["易方达基金", "华夏基金", "嘉实基金"],
    #     category_name="金融科技与IT服务",
    #     analyses_requested=[
    #         "pestle",           # 宏观环境分析（金融监管政策等）
    #         "porter",           # 行业竞争分析
    #         "switching_barriers", # 系统转换壁垒
    #         "cost_drivers",     # 成本结构分析
    #     ],
    #     region="中国",
    #     annual_spend=25000000,       # 年度IT支出（元）
    #     incumbent_suppliers=[
    #         "恒生电子",         # 核心交易系统
    #         "金证股份",         # 基金业务系统
    #         "顶点软件",         # 资管系统
    #         "东方财富",         # 数据服务
    #         "同花顺",          # 金融数据
    #     ],
    # )
    # procurement_workflow.print_response(
    #     input=analysis_details,
    #     stream=True,
    #     stream_events=True,
    # )